import {Button, Card, Divider, message, Skeleton, Space, Tag, Typography} from "antd";
import {useEffect, useState} from "react";
import {
    CalendarOutlined,
    CheckCircleOutlined,
    EditOutlined,
    EnvironmentOutlined,
    IdcardOutlined,
    InfoOutlined,
    LockOutlined,
    PoweroffOutlined,
    SafetyCertificateOutlined,
    TeamOutlined,
    UserOutlined
} from "@ant-design/icons";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";
import '../../css/personal/Personal.css';
import BackButton from "../../components/button/BackButton";
import EditPersonalModal from "../../components/personal/EditPersonalModal";
import EditPasswordModal from "../../components/personal/EditPasswordModal";

const Personal = () => {
    const [messageApi, contextHolder] = message.useMessage();

    // 状态管理
    const [currentUserId] = useState(RequestUtils.getCurrentUserInfo().userId);
    const [currentUserInfo, setCurrentUserInfo] = useState({});
    const [existRoles, setExistRoles] = useState([]);
    const [existPermissions, setExistPermissions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [completionRate, setCompletionRate] = useState(0);
    const [editPersonalParam, setEditPersonalParam] = useState({
        visible: false,
        userInfo: {
            userId: "",
            userNickname: "",
            userGender: null,
            userBirthDate: "",
            userAddress: "",
            userIntroduction: ""
        }
    });
    const [editPasswordParam, setEditPasswordParam] = useState({
        visible: false,
        userInfo: {
            userId: "",
            oldPassword: "",
            newPassword: "",
            confirmPassword: ""
        }
    });

    // 页面初始化加载数据
    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                // 并行请求数据
                const [userInfoRes, rolesRes, permissionsRes] = await Promise.all([
                    RequestUtils.post(Apis.user.searchUserById, {id: currentUserId}),
                    RequestUtils.post(Apis.permission.searchRoleRelationByUserId, {id: currentUserId}),
                    RequestUtils.post(Apis.permission.searchUserPermissionByUserId, {id: currentUserId})
                ]);

                setCurrentUserInfo(userInfoRes);
                setExistRoles(rolesRes.relationRoles || []);
                setExistPermissions(permissionsRes.permissions || []);
                setCompletionRate(getCompletionRate(userInfoRes));
            } catch (err) {
                messageApi.error("数据加载失败: " + (err.message || "未知错误"));
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [currentUserId, messageApi]);

    // 获取资料完成度颜色
    const getCompletionColor = (rate) => {
        if (rate < 30) return '#f5222d';
        if (rate < 70) return '#fa8c16';
        return '#52c41a';
    };

    return (
        <div className="personal-container">
            {contextHolder}

            <BackButton
                message="返回上一级页面"
                backToLink={-1}
            />

            <div className="page-header">
                <Title level={2} className="page-title">
                    <UserOutlined className="title-icon"/>
                    个人信息
                </Title>
            </div>

            <div className="main-content">
                {/* 左侧信息栏 */}
                <div className="profile-sidebar">
                    <Card className="profile-card">
                        <div className="profile-header">
                            <InitialAvatar nickname={currentUserInfo.userNickname}/>
                            <div className="profile-name-section">
                                <Title level={3} className="profile-name">
                                    {loading ? <Skeleton.Input active
                                                               style={{width: 120}}/> : currentUserInfo.userNickname || "用户"}
                                </Title>
                                <div className="user-id">
                                    <IdcardOutlined className="id-icon"/>
                                    <Text type="secondary">用户ID: {currentUserId}</Text>
                                </div>
                            </div>
                        </div>

                        <Divider className="profile-divider"/>

                        <div className="profile-completion">
                            <div className="completion-header">
                                <Text>资料完成度</Text>
                                <Tag color={getCompletionColor(completionRate)} className="completion-badge">
                                    {completionRate}%
                                </Tag>
                            </div>
                            <div className="progress-bar">
                                <div
                                    className="progress-fill"
                                    style={{
                                        width: `${completionRate}%`,
                                        backgroundColor: getCompletionColor(completionRate)
                                    }}
                                ></div>
                            </div>
                            <Text type="secondary" className="completion-text">
                                完善个人信息，提升账号安全性
                            </Text>
                        </div>

                        <Divider className="profile-divider"/>

                        <div className="account-status">
                            <div className="status-item">
                                <Text>账号状态</Text>
                                <Space className="status-value">
                                    <CheckCircleOutlined className="status-icon"/>
                                    <Text>正常</Text>
                                </Space>
                            </div>
                        </div>
                    </Card>
                </div>

                {/* 右侧详细信息 */}
                <div className="profile-details">
                    {/* 基本资料卡片 */}
                    <Card className="detail-card">
                        <div className="card-content">
                            <Title level={4} className="card-title">
                                <UserOutlined className="card-icon"/>
                                基本资料
                                <Button
                                    color="purple" variant="solid"
                                    style={{marginLeft: '25px'}}
                                    onClick={() => {
                                        setEditPersonalParam({
                                            visible: true,
                                            userInfo: {
                                                userId: currentUserInfo.id,
                                                userNickname: currentUserInfo.userNickname,
                                                userGender: currentUserInfo.userGender,
                                                userBirthDate: currentUserInfo.userBirthDate,
                                                userAddress: currentUserInfo.userAddress,
                                                userIntroduction: currentUserInfo.userIntroduction
                                            }
                                        })
                                    }}
                                >
                                    <EditOutlined/>编辑个人信息
                                </Button>

                                <Button
                                    color="pink" variant="solid"
                                    style={{marginLeft: '15px'}}
                                    onClick={() => {
                                        setEditPasswordParam({
                                            visible: true,
                                            userInfo: {
                                                userId: currentUserInfo.id,
                                                oldPassword: "",
                                                newPassword: "",
                                                confirmPassword: ""
                                            }
                                        })
                                    }}
                                >
                                    <SafetyCertificateOutlined/>修改密码
                                </Button>

                                <Button
                                    color="red" variant="solid"
                                    style={{marginLeft: '15px', width: '100px'}}
                                    onClick={() => {
                                        // 等待1秒
                                        setTimeout(() => {
                                            messageApi.success("退出登录成功");
                                            RequestUtils.clearToken();
                                        }, 1000);
                                        window.location.replace("/login");
                                    }}
                                >
                                    <PoweroffOutlined/>退出登录
                                </Button>
                            </Title>

                            <div className="info-grid">
                                <InfoItem
                                    icon={<UserOutlined/>}
                                    label="用户账号"
                                    value={currentUserInfo.userAccount}
                                    loading={loading}
                                    isImportant={true}
                                    bgColor="#f0f7ff"
                                />
                                <InfoItem
                                    icon={<UserOutlined/>}
                                    label="用户昵称"
                                    value={currentUserInfo.userNickname}
                                    loading={loading}
                                    bgColor="#f9f0ff"
                                />
                                <InfoItem
                                    icon={<UserOutlined/>}
                                    label="用户性别"
                                    value={currentUserInfo.userGenderValue}
                                    loading={loading}
                                    bgColor="#fff0f6"
                                />
                                <InfoItem
                                    icon={<CalendarOutlined/>}
                                    label="出生日期"
                                    value={currentUserInfo.userBirthDate}
                                    loading={loading}
                                    bgColor="#fff7e6"
                                />
                                <InfoItem
                                    icon={<EnvironmentOutlined/>}
                                    label="所在地区"
                                    value={currentUserInfo.userAddress}
                                    loading={loading}
                                    bgColor="#f6ffed"
                                />
                            </div>

                            {/* 个人介绍 */}
                            <div style={{marginTop: 24}}>
                                <Title level={4} className="card-title">
                                    <InfoOutlined className="card-icon"/>
                                    个人介绍
                                </Title>
                                <div className="introduction-container">
                                    {loading ? (
                                        <Skeleton active paragraph={{rows: 3}}/>
                                    ) : (
                                        <Paragraph className="introduction-content">
                                            {currentUserInfo.userIntroduction ||
                                                <Text type="secondary">-- 暂无个人介绍 --</Text>}
                                        </Paragraph>
                                    )}
                                </div>
                            </div>
                        </div>
                    </Card>

                    {/* 角色和权限卡片 */}
                    <div className="roles-permissions-grid">
                        {/* 角色信息卡片 */}
                        <Card className="role-permission-card">
                            <Title level={4} className="card-title">
                                <TeamOutlined className="card-icon"/>
                                拥有角色
                            </Title>
                            <div className="role-permission-content">
                                {loading ? (
                                    <Skeleton active paragraph={{rows: 2}}/>
                                ) : (
                                    <Space size="middle" wrap className="tags-container">
                                        {existRoles.length > 0 ? (
                                            existRoles.map(role => (
                                                <Tag
                                                    key={role.roleId}
                                                    color={getAvatarColor(role.roleName)}
                                                    icon={<TeamOutlined/>}
                                                    className="custom-tag"
                                                >
                                                    {role.roleName}
                                                </Tag>
                                            ))
                                        ) : (
                                            <Text type="secondary">暂无角色信息</Text>
                                        )}
                                    </Space>
                                )}
                            </div>
                        </Card>

                        {/* 权限信息卡片 */}
                        <Card className="role-permission-card">
                            <Title level={4} className="card-title">
                                <LockOutlined className="card-icon"/>
                                拥有权限
                            </Title>
                            <div className="role-permission-content">
                                {loading ? (
                                    <Skeleton active paragraph={{rows: 3}}/>
                                ) : (
                                    <Space size="middle" wrap className="tags-container">
                                        {existPermissions.length > 0 ? (
                                            existPermissions.map(permission => (
                                                <Tag
                                                    key={permission.id}
                                                    className="custom-tag"
                                                    color={"green"}
                                                >
                                                    {permission.permissionName}
                                                </Tag>
                                            ))
                                        ) : (
                                            <Text type="secondary">暂无权限信息</Text>
                                        )}
                                    </Space>
                                )}
                            </div>
                        </Card>
                    </div>
                </div>
            </div>

            {/* 修改个人信息modal */}
            <EditPersonalModal
                editPersonalParam={editPersonalParam}
                setEditPersonalParam={setEditPersonalParam}
            />

            {/* 修改密码modal */}
            <EditPasswordModal
                editPasswordParam={editPasswordParam}
                setEditPasswordParam={setEditPasswordParam}
            />

        </div>
    );
};


const {Title, Text, Paragraph} = Typography;

// 定义10种柔和不刺眼的固定颜色（低饱和度、高亮度）
const SOFT_COLORS = [
    '#1890ff', // 亮蓝
    '#52c41a', // 亮绿
    '#fa8c16', // 亮橙
    '#f5222d', // 亮红
    '#722ed1', // 亮紫
    '#13c2c2', // 亮青
    '#eb2f96', // 亮粉
    '#faad14', // 亮黄
    '#2f54eb', // 深蓝
    '#8254de'  // 深紫
];

// 将字符串转换为数字索引（取模10）
const getAvatarColor = (str) => {
    // 处理空值，返回第一种默认颜色
    if (!str || typeof str !== 'string') return SOFT_COLORS[0];

    // 字符串转数字：累加字符Unicode编码，生成哈希值
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        // 累加每个字符的编码，乘以质数31减少碰撞
        hash = (hash * 31 + str.charCodeAt(i)) % 1000000;
    }

    // 取模10，得到0-9的索引，对应固定颜色数组
    const index = hash % SOFT_COLORS.length;
    return SOFT_COLORS[index];
};

// 自定义头像组件 - 显示昵称首字
const InitialAvatar = ({nickname}) => {
    const initial = nickname ? nickname.charAt(0) : 'U';
    const bgColor = getAvatarColor(nickname || 'user');

    return (
        <div className="avatar-container" style={{backgroundColor: bgColor}}>
            <span className="avatar-initial">{initial}</span>
        </div>
    );
};

// 信息项组件
const InfoItem = ({icon, label, value, loading, isImportant = false, bgColor}) => {
    return (
        <div className="info-item" style={{backgroundColor: bgColor || '#ffffff'}}>
            <div className="info-item-header">
                <span className="info-icon" style={{color: getIconColor(label)}}>{icon}</span>
                <span className="info-label">{label}</span>
                {isImportant && (
                    <Tag color="orange" size="small" className="important-badge">重要</Tag>
                )}
            </div>
            {loading ? (
                <Skeleton.Input active style={{width: '100%', height: 24}}/>
            ) : (
                <div className="info-value">
                    {value || <Text type="secondary">-- 未设置 --</Text>}
                </div>
            )}
        </div>
    );
};

// 根据标签获取图标颜色
const getIconColor = (label) => {
    const colorMap = {
        '用户账号': '#1890ff',
        '用户昵称': '#722ed1',
        '用户性别': '#eb2f96',
        '出生日期': '#fa8c16',
        '所在地区': '#52c41a',
        '个人介绍': '#13c2c2'
    };
    return colorMap[label] || '#8c8c8c';
};

// 获取资料完成度
const getCompletionRate = (userInfo) => {
    if (!userInfo) return 0;

    const fields = [
        'userAccount',
        'userNickname',
        'userGender',
        'userBirthDate',
        'userAddress',
        'userIntroduction'
    ];

    let completed = 0;
    fields.forEach(field => {
        if (userInfo[field]) completed++;
    });

    return Math.round((completed / fields.length) * 100);
};

export default Personal;
